package com.tensquare.qa.controller;

import com.sun.net.httpserver.HttpServer;
import com.tensquare.qa.client.LabelClient;
import com.tensquare.qa.pojo.Problem;
import com.tensquare.qa.service.ProblemService;
import common.entity.PageResult;
import common.entity.Result;
import common.entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Feng.Wang
 * @Company: Zelin.ShenZhen
 * @Description:
 * @Date: Create in 2019/3/23 16:50
 */
@RestController
@RequestMapping("/problem")
@CrossOrigin
public class ProblemController {
    @Autowired
    private ProblemService problemService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LabelClient labelClient;
    /**
     * 查询最新问题列表
     * @param label
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/newlist/{label}/{page}/{size}",method = RequestMethod.GET)
    public Result findNewList(@PathVariable String label,@PathVariable int page,@PathVariable int size){
        Page<Problem> pageData = problemService.findNewlistByLabelId(label, page, size);
        return new Result(true, StatusCode.OK,"查询最新问题列表成功！",new PageResult<>(pageData.getTotalElements(),pageData.getContent()));

    }
    @RequestMapping(method=RequestMethod.POST)
    public Result add(@RequestBody Problem problem ){
        Claims claims = (Claims) request.getAttribute("user_claims");
        String roles = (String) claims.get("roles");
        if(!"user".equals(roles)){  //当前用户必须以普通用户身份登录才可发布问题
            return new Result(false,StatusCode.ACCESSERROR,"权限不足");
        }
        problem.setUserid(claims.getId());
        problemService.add(problem);
        return new Result(true,StatusCode.OK,"发布成功");
    }

    /**
     * 根据标签id查询标签
     * @param labelId
     * @return
     */
    @RequestMapping(value = "/label/{labelId}",method = RequestMethod.GET)
    public Result findById(@PathVariable String labelId){
        return labelClient.findById(labelId);
    }
}
